import {
	defineStore
} from 'pinia';
/**
 * actions方法名为 state字段前拼接GET
 */
import {
	getDept,
	getPost,
	infoUserProfile
} from '@/api/public';
import {
	getList
} from '@/api/system';
import {
	treeDchildren
} from '@/utils/tree.js';
export default defineStore({
	id: 'com',
	state: () => ({
		deptTree: [],
		useList: [],
		postList: [],
		issueClassifyList: [],
		userInfo: {},
		roles: []
	}),
	actions: {
		// 获取部门树
		GETdeptTree(deptId) {
			return new Promise((resolve, reject) => {
				if (this.deptTree.length > 0) {
					resolve(this.deptTree);
				} else {
					getDept({
						deptId
					}).then((res) => {
						this.deptTree = treeDchildren(res.data);
						console.log(this.deptTree);
						resolve(this.deptTree);
					}).catch((err) => {
						reject(err);
					});
				}
			});
		},
		// 获取用户列表
		GETuseList() {
			return new Promise((resolve, reject) => {
				getList().then((res) => {
					this.useList = res.data.map((item) => ({
						dictLabel: item.userName,
						dictValue: item.id,
					}));
					resolve(this.useList);
				}).catch((err) => {
					reject(err);
				});
			});
		},
		// 部门
		GETpostList() {
			return new Promise((resolve, reject) => {
				if (this.postList.length > 0) {
					resolve(this.postList);
				} else {
					getPost().then((res) => {
						this.postList = res.data.map((item) => ({
							dictLabel: item.postName,
							dictValue: item.id,
						}));
						resolve(this.postList);
					}).catch((err) => {
						reject(err);
					});
				}
			});
		},
		// 获取用户信息
		GETpersonInfo() {
			return new Promise((resolve, reject) => {
				infoUserProfile().then((res) => {
					const {
						user,
						roles: Roles,
						posts
					} = res?.data;
					if (Roles.length) {
						// 验证返回的roles是否是一个非空数组
						this.roles = Roles;
					} else {
						this.roles = ['ROLE_DEFAULT'];
					}
					this.userInfo = {
						userId: user.id,
						userName: user.userName,
						nickName: user.nickName,
						deptId: user.deptId,
						avatar: user.avatar,
						phonenumber: user.phonenumber,
						email: user.email,
						posts: posts.join('')
					};
					resolve(this.userInfo);
				}).catch((error) => {
					reject(error);
				});
			});
		},
	},
	unistorage: true
});